<?php
/**
 * 提供网站端或者外部访问的接口相关
 */
namespace app\controllers\marketing;

use Yii;
use app\components\redis\RedisMarketingEmail;
use app\models\marketing\UserGoods;
use app\models\marketing\GoodsData;
use app\components\redis\RedisLock;
use app\components\mq\MqComponent;
use app\models\WebsiteGoods;
use app\components\TemplateMarket;
use app\models\marketing\User;
use app\models\Elog;


class ApiSyncDataController extends ApiController
{
    protected $oldKeyCode = 'c346eb79b0b21b26a9fMFj8M7xPMoO0O';
    protected $newKeyCode = '3407e2f05fd201cf4aa534464deffd23';
    protected $affiliateKeyCode = 'KhAqmjbtrUBX3RyQ';
    protected $goodsDataKeyCode = 'xef5pBDje6dz9tcBQCP7JT842w5eVs8X';
    protected $siteIdArr = [
        'gamiss.com' => 22,
        'nastydress.com' => 18,
        'trendsgal.com' => 16,
        'twinkledeals.com' => 17,
        'zaful.com' => 19,
        'rosewholesale.com'  => 10,
        'sammydress.com' => 3,
        'stylebest.com' => 23,
        'dresslily.com' => 6,
        'rosegal.com' => 11,
        'gearbest.com'=>12,
    ];
    
    /**
     * 接收网站购物车用户的商品信息
     * 
     * @example /marketing/api-sync-data/user-cartgoods-rabbitmq?site=marketing_email 访问地址
     * 
     */
    public function actionUserCartgoodsRabbitmq()
    {
        // 设置脚本不超时
        set_time_limit(0);
        
        try {
            $redis = new RedisMarketingEmail();
            
            //同一网站两次同步数据请求间隔需大于10分钟
            $redisLock = new RedisLock($redis, "actionUserCartgoodsRabbitmq", 600);
            
            if ($redisLock->translock() === false) {
                $msg = 'the process fail to get the lock,please wait!';
                Elog::logCrontab($msg, 'actionUserGoodsRabbitMq','info');
                echo '有请求在处理中，拒绝该请求！';
                exit;
            }
            
            // 网站商品数据
            $obj = new WebsiteGoods();
            
            // 从MQ接收数据
            MqComponent::receiveQueueData('cart_EMP',$obj,'saveWebsiteCartGoods');
            
            // 正常结束-释放锁
            $redisLock->unlock();
            
            echo 'END';
            
        }catch(\yii\console\Exception $e)
        {
            // 接收异常
            $msg='actionUserCartgoodsRabbitmq Exception :'.$e->getMessage().' ';
            
            // 记录入elog
            Elog::logCrontab($msg, 'actionUserGoodsRabbitMq','exception');
            
            // 异常结束-释放锁
            if(!empty($redisLock)) {
                $redisLock->unlock();
            }
        }
    }
    
    /**
     * 接收网站浏览商品记录信息
     * 
     * @example /marketing/api-sync-data/user-browse-goods-rabbitmq?site=marketing_email 访问地址
     */
    public function actionUserBrowseGoodsRabbitmq()
    {
        set_time_limit(0);
        
        // 从MQ接收数据
        try {
            $redis = new RedisMarketingEmail();
            
            //同一网站两次同步数据请求间隔需大于10分钟
            $redisLock = new RedisLock($redis, "actionUserBrowseGoodsRabbitMq", 600);
            
            if ($redisLock->translock() === false) {
                $msg = 'the process fail to get the lock,please wait!';
                Elog::logCrontab($msg, 'actionUserBrowseGoodsRabbitMq','info');
                echo '有请求在处理中，拒绝该请求！';
                exit;
            }
            
            // 网站商品数据
            $obj = new WebsiteGoods();
             
            // 从MQ接收数据
            MqComponent::receiveQueueData('browsingHistory_EMP',$obj,'saveWebsiteBrowseGoods');
            
            // 正常结束-释放锁
            $redisLock->unlock();
            
            echo 'END';
            
        } catch (\yii\console\Exception $e) {
            // 接收异常
            $msg='actionUserBrowseGoodsRabbitMq Exception :'.$e->getMessage().' ';
            
            // 记录入elog
            Elog::logCrontab($msg, 'actionUserBrowseGoodsRabbitMq','exception');
            
            // 异常结束-释放锁
            if(!empty($redisLock)) {
                $redisLock->unlock();
            }
        }
    }
    
     /**
     * Affiliate网站端推送数据接口
     */
    public function actionUserGoodsAffiliate() 
    {
        set_time_limit(0);
        
       
        $mothod = strtolower(Yii::$app->request->getMethod());  
        $formData = Yii::$app->request->$mothod();
        $returnInfo = [];
      
        if (empty($formData['token']) || empty($formData['data'])) {
            $returnInfo['errorCode'] = 1;
            $returnInfo['info'] = '数据不完整';
            echo json_encode($returnInfo);
            exit;
        }

        // 判断数据是否异常
        if ($formData['token'] != md5($this->affiliateKeyCode . $formData['data'])) {
            $returnInfo['errorCode'] = 1;
            $returnInfo['info'] = 'token错误';
            echo json_encode($returnInfo);
            exit;
        } else {
            $data = json_decode($formData['data'],true);
            if ($data) {
                if (empty($data['webId'])) { // 没有传递webId
                    $returnInfo['errorCode'] = 1;
                    $returnInfo['info'] = '必须传递webId!';
                    echo json_encode($returnInfo);
                    exit;
                } else {
                    if (!empty($data['templateInfo'])) { // 邮件模板入库
                        try {
                            $TemplateMarket = new TemplateMarket();
                            $returnFlag = $TemplateMarket->affiliateAddTemplate($data);
                            if ($returnFlag) {
                                $returnInfo['errorCode'] = 0;
                                $returnInfo['info'] = '成功!';
                                echo json_encode($returnInfo);
                                exit;
                            } else {
                                $returnInfo['errorCode'] = 1;
                                $returnInfo['info'] = '数据库忙，添加或更改模板失败!';
                                echo json_encode($returnInfo);
                                exit;
                            }
                        } catch (\Exception $ex) {
                            $returnInfo['errorCode'] = 1;
                            $returnInfo['info'] = $ex->getMessage();
                            echo json_encode($returnInfo);
                            Elog::logCrontab($ex->getMessage(), 'actionUserGoodsAffiliate','exception');
                            exit;
                        }
                    } elseif(!empty($data['userEmail'])) { // 用户入库
                        $userModel = new User();
                        $trans = Yii::$app->db->beginTransaction(); // 开启事务，保证一批的数据可以插入成功
                        
                        try {
                            $userModel->saveAffiliateData($data);
                            $trans->commit();
                            $returnInfo['errorCode'] = 0;
                            $returnInfo['info'] = '成功!';
                            echo json_encode($returnInfo);
                            exit;
                        } catch (\Exception $ex) {
                            $trans->rollBack();
                            $returnInfo['errorCode'] = 1;
                            $returnInfo['info'] = $ex->getMessage();
                            echo json_encode($returnInfo);
                            Elog::logCrontab($ex->getMessage(), 'actionUserGoodsAffiliate','exception');
                            exit;
                        }
                    }
                }
            } else {
                $returnInfo['errorCode'] = 1;
                $returnInfo['info'] = 'data不是json格式';
                echo json_encode($returnInfo);
                exit;
            }
        }
    }
    
    // 商品数据同步接口
    public function actionGoodsData()
    {
        set_time_limit(0);
        $mothod = strtolower(Yii::$app->request->getMethod());  
        $formData = Yii::$app->request->$mothod();
        if ($formData) {
            if (!isset($formData['site_name']) || !$formData['site_name']) { // 说明没传网站
                $returnData['code'] = 1;
                $returnData['info'] = 'site info is empty';  
                die(json_encode($returnData));
            }
            
            if (isset($this->siteIdArr[$formData['site_name']])) {
                $siteId  = $this->siteIdArr[$formData['site_name']];
                $formData['siteId'] = $siteId;
            } else {
               $returnData['code'] = 5;
               $returnData['info'] = 'site info is error';  
               die(json_encode($returnData));
            }
            if (!isset($formData['keys_code']) || $this->goodsDataKeyCode != $formData['keys_code']) { // 说明秘钥不正确
                $returnData['code'] = 2;
                $returnData['info'] = 'Error,key code error';  
                die(json_encode($returnData));
            }
            if (!isset($formData['data']) || !$formData['data']) { // 说明没传商品信息
                $returnData['code'] = 3;
                $returnData['info'] = 'goods data is empty';  
                die(json_encode($returnData));
            }
            $goodsData = json_decode($formData['data'], true);
            if (!$goodsData) {
                $returnData['code'] = 4;
                $returnData['info'] = 'data is not json';  
                die(json_encode($returnData));
            } 
            
            // 往数据库中添加数据
            $goodsData = new GoodsData();
            $returnFlag = $goodsData->dealData($formData);
            if ($returnFlag) {
                $returnData['code'] = 0;
                $returnData['info'] = 'success!';  
            } else {
                $returnData['code'] = 7;
                $returnData['info'] = 'system is busyness!';  
            }
        } else {
            $returnData['code'] = 6;
            $returnData['info'] = 'data is incomplete';  
        }
        die(json_encode($returnData));
    }
    // 旧的营销邮件同步数据相关
    public function actionUserGoods()
    {
        set_time_limit(0);
        $mothod = strtolower(Yii::$app->request->getMethod());  
        $formData = Yii::$app->request->$mothod();
        $is_gzip = isset($formData['is_gzip']) ? $formData['is_gzip'] : 0;
        if (isset($formData['data']) && empty($is_gzip)) {
            
            $formData['data'] = urldecode($formData['data']);
        }
        if ( $is_gzip == 1 ) {
           $formData['data'] = gzuncompress(base64_decode($formData['data']));
        } 
        
        if (!empty($formData['site_name']) && $formData['site_name'] == 'dresslily.com' ) {
            file_put_contents(ROOT_PATH.'/upload/dresslily_com_data.txt',var_export($formData,true));
        }
        // file_put_contents(ROOT_PATH.'/upload/bnbnbn21.txt',var_export($formData,true),FILE_APPEND);
        if ($formData) {
            
            if (!isset($formData['site_name']) || !$formData['site_name']) {
                exit('site info is empty'); 
            }
            
            if (isset($this->siteIdArr[$formData['site_name']])) {
                $siteId  = $this->siteIdArr[$formData['site_name']];
                $formData['siteId'] = $siteId;
            } else {
                exit('site is error'); 
            }
            $userGoods = new UserGoods();
           
            // 格式判断
            $result = [];
            if (isset($formData['data'])) {
                if (false !== stripos($_SERVER['CONTENT_TYPE'], "application/x-www-form-urlencoded")) {
                    $isJsonData = json_decode($formData['data'], true);
                } else {
                    $isJsonData = json_decode(urldecode($formData['data']), true);
                }
               
                if (isset($isJsonData) && $isJsonData && empty($formData['is_gzip'])) {
                   
                    if (!isset($formData['keys_code']) || $this->newKeyCode != $formData['keys_code']) {
                        die('Error,key code error'); // 验证密钥是否正确 
                    }
                    $formData['data'] = $isJsonData;
                   
                    if (!empty($formData['site_name']) && $formData['site_name'] == 'gearbest.com') {
                        $returnTmp = $userGoods->dealNewData($formData);
                        if (!empty($returnTmp['code'])) {
                            $return['code'] = $returnTmp['code'];
                        }
                        if (!empty($returnTmp['cart_id'])) {
                            $return['cart_id'] = $returnTmp['cart_id'];
                        }
                        if (!empty($returnTmp['msg'])) {
                            $return['status'] = $returnTmp['msg'];
                        }
                    } else {
                        $return = $userGoods->dealNewData($formData);
                    }
                    echo json_encode($return);
                } else {
                    if (!isset($formData['keys_code']) || $this->oldKeyCode != $formData['keys_code']) {
                        die('Error,key code error'); // 验证密钥是否正确 
                    }
                    
                    if (!empty($formData['site_name']) && $formData['site_name'] == 'gearbest.com') {
                        $returnTmp = $userGoods->dealOldData($formData);
                        if (!empty($returnTmp['msg'])) {
                            $return['status'] = $returnTmp['msg'];
                        }
                        
                        if (!empty($returnTmp['cart_id'])) {
                            $return['cart_id'] = $returnTmp['cart_id'];
                        }
                    } else {
                        $return = $userGoods->dealOldData($formData);
                    }
                    
                    echo serialize($return);
                   
                }
            } else {
                echo json_encode($result);
            }
        } else {
            die('data is incomplete');
        }
       
    }
   
    // 数据入库
    
   
    
}
